import type { BaseResponse } from "@/api/response";
import { http } from "@/utils/http";
import { ClusterRole, type RoleList, type ClusterRoleList } from "./types";

export class K8sRoleRepo {
  roleUrl = cluster_name => {
    return `/api/v1/proxy/${cluster_name}/k8s/apis/rbac.authorization.k8s.io/v1/roles`;
  };

  namespaceRoleUrl = (cluster_name, namespace) => {
    return `/api/v1/proxy/${cluster_name}/k8s/apis/rbac.authorization.k8s.io/v1/namespaces/${namespace}/roles`;
  };

  listRoles(cluster_name, namespace, search, keywords, pageNum, pageSize) {
    let url = this.roleUrl(cluster_name);
    if (namespace !== "") {
      url = this.namespaceRoleUrl(cluster_name, namespace);
    }
    const params = {};
    if (search) {
      params["search"] = true;
      if (keywords) {
        params["keywords"] = keywords;
      }
      if (pageNum && pageSize) {
        params["pageNum"] = pageNum;
        params["pageSize"] = pageSize;
      }
    }
    return http.get(url, params);
  }

  listNamespaceRoles(cluster_name, namespace): BaseResponse<RoleList> {
    let url = this.namespaceRoleUrl(cluster_name, namespace);
    return http.get(url);
  }

  deleteRole(cluster_name, namespace, name) {
    return http.delete(
      `${this.namespaceRoleUrl(cluster_name, namespace)}/${name}`
    );
  }

  getRole(cluster_name, namespace, name) {
    return http.get(
      `${this.namespaceRoleUrl(cluster_name, namespace)}/${name}`
    );
  }

  createRole(cluster_name, namespace, data) {
    return http.post(`${this.namespaceRoleUrl(cluster_name, namespace)}`, data);
  }

  updateRole(cluster_name, namespace, name, data) {
    return http.put(
      `${this.namespaceRoleUrl(cluster_name, namespace)}/${name}`,
      data
    );
  }
}
